<template>
  <div class="news-create">
    <div class="container">
      <div class="back-link">
        <router-link to="/news" class="back-btn">« 返回新闻列表</router-link>
      </div>
      
      <div class="create-header">
        <h1>新建新闻</h1>
      </div>
      
      <div class="create-form">
        <div class="form-group">
          <label for="news-title">标题</label>
          <input type="text" id="news-title" v-model="newsItem.title" class="form-control" placeholder="请输入新闻标题">
          <div class="error-message" v-if="errors.title">{{ errors.title }}</div>
        </div>
        
        <div class="form-group">
          <label for="news-date">发布时间</label>
          <input type="text" id="news-date" v-model="newsItem.releaseTime" class="form-control" placeholder="格式: 2025-10-13 10:00:00">
          <div class="error-message" v-if="errors.releaseTime">{{ errors.releaseTime }}</div>
        </div>
        
        <div class="form-group">
          <label for="news-content">内容</label>
          <textarea id="news-content" v-model="newsItem.content" class="form-control" rows="15" placeholder="请输入新闻内容"></textarea>
          <div class="error-message" v-if="errors.content">{{ errors.content }}</div>
        </div>
        
        <div class="form-actions">
          <button @click="saveNews" class="btn btn-save" :disabled="loading">
            {{ loading ? '保存中...' : '保存新闻' }}
          </button>
          <button @click="cancel" class="btn btn-cancel" :disabled="loading">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { newsApi } from '@/api/news'

export default {
  name: 'NewsCreate',
  data() {
    return {
      newsItem: {
        title: '',
        releaseTime: '',
        content: ''
      },
      errors: {
        title: '',
        releaseTime: '',
        content: ''
      },
      loading: false
    };
  },
  methods: {
    validateForm() {
      let isValid = true;
      
      // 重置错误消息
      this.errors = {
        title: '',
        releaseTime: '',
        content: ''
      };
      
      // 验证标题
      if (!this.newsItem.title.trim()) {
        this.errors.title = '请输入新闻标题';
        isValid = false;
      }
      
      // 验证发布时间
      if (!this.newsItem.releaseTime.trim()) {
        this.errors.releaseTime = '请输入发布时间';
        isValid = false;
      } else {
        // 验证时间格式: YYYY-MM-DD HH:mm:ss
        const timePattern = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
        if (!timePattern.test(this.newsItem.releaseTime.trim())) {
          this.errors.releaseTime = '时间格式不正确，请使用格式: YYYY-MM-DD HH:mm:ss (例如: 2025-10-13 10:00:00)';
          isValid = false;
        } else {
          // 验证日期是否有效
          const dateTime = new Date(this.newsItem.releaseTime.trim());
          if (isNaN(dateTime.getTime())) {
            this.errors.releaseTime = '请输入有效的日期时间';
            isValid = false;
          }
        }
      }
      
      // 验证内容
      if (!this.newsItem.content.trim()) {
        this.errors.content = '请输入新闻内容';
        isValid = false;
      }
      
      return isValid;
    },
    
    // 验证并返回时间字符串（用户手动输入的格式已经是正确的）
    formatDateTime(timeString) {
      if (!timeString) return '';
      return timeString.trim();
    },
    
    // 解析JSON时处理大整数ID，避免精度丢失
    parseJSONWithBigInt(jsonString) {
      try {
        // 使用正则表达式将大数字ID转换为字符串，避免精度丢失
        const fixedJsonString = jsonString.replace(
          /"(id|userId|teamId|questionId|homeworkId|newsId)":\s*(\d{15,})/g,
          '"$1":"$2"'
        );
        
        console.log('修复大整数后的JSON:', fixedJsonString);
        
        return JSON.parse(fixedJsonString);
      } catch (error) {
        console.error('JSON解析失败，使用原始解析:', error);
        return JSON.parse(jsonString);
      }
    },
    
    // 获取用户ID - 从JWT令牌中解析
    getUserId() {
      try {
        // 首先尝试从JWT令牌中解析用户ID
        const token = localStorage.getItem('token');
        if (token) {
          // JWT令牌由三部分组成，用.分隔：header.payload.signature
          const parts = token.split('.');
          if (parts.length === 3) {
            // 解码payload部分（base64url编码）
            const payload = parts[1];
            // 添加必要的padding
            const paddedPayload = payload + '='.repeat((4 - payload.length % 4) % 4);
            // base64url解码
            const decodedPayload = atob(paddedPayload.replace(/-/g, '+').replace(/_/g, '/'));
            
            console.log('JWT payload原始字符串:', decodedPayload);
            
            // 使用自定义解析处理大整数ID
            const payloadObj = this.parseJSONWithBigInt(decodedPayload);
            
            console.log('JWT payload解析结果:', payloadObj);
            
            // 从claims中获取id
            if (payloadObj.claims && payloadObj.claims.id) {
              const userId = payloadObj.claims.id;
              console.log('从JWT令牌中获取到的userId:', userId, '类型:', typeof userId, '长度:', userId.length);
              return userId;
            }
          }
        }
        
        // 如果JWT解析失败，回退到localStorage中的userInfo
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        const fallbackId = userInfo.userId || userInfo.id || '';
        console.log('回退使用localStorage中的userId:', fallbackId);
        return fallbackId;
        
      } catch (error) {
        console.error('解析JWT令牌失败:', error);
        
        // 解析失败时使用localStorage中的用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        const fallbackId = userInfo.userId || userInfo.id || '';
        console.log('解析失败，使用localStorage中的userId:', fallbackId);
        return fallbackId;
      }
    },
    async saveNews() {
      if (this.validateForm()) {
        this.loading = true;
        
        try {
          // 获取用户ID
          const userId = this.getUserId();
          if (!userId) {
            this.$message?.error('用户信息获取失败，请重新登录');
            return;
          }
          
          // 格式化发布时间
          const formattedTime = this.formatDateTime(this.newsItem.releaseTime);
          
          // 准备API请求数据
          const requestData = {
            userId: userId,
            title: this.newsItem.title,
            releaseTime: formattedTime,
            content: this.newsItem.content
          };
          
          console.log('发送新建新闻请求:', requestData);
          
          // 调用API创建新闻
          const response = await newsApi.createNews(requestData);
          
          console.log('新建新闻成功:', response);
          
          // 移除成功提示弹窗，改善用户体验
          // if (this.$message) {
          //   this.$message.success('新闻创建成功！');
          // } else {
          //   alert('新闻创建成功！');
          // }
          
          // 设置成功标记到sessionStorage
          sessionStorage.setItem('showNewsCreateSuccess', 'true');
          
          // 返回新闻列表页
          this.$router.push('/news');
          
        } catch (error) {
          console.error('创建新闻失败:', error);
          
          // 显示错误消息
          const errorMessage = error.response?.data?.message || error.message || '创建新闻失败，请重试';
          if (this.$message) {
            this.$message.error(errorMessage);
          } else {
            alert(errorMessage);
          }
        } finally {
          this.loading = false;
        }
      }
    },
    cancel() {
      // 返回新闻列表页
      this.$router.push('/news');
    }
  }
};
</script>

<style scoped>
.news-create {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 30px;
}

.back-link {
  margin-bottom: 20px;
}

.back-btn {
  color: #3e8ef7;
  text-decoration: none;
  font-size: 14px;
}

.back-btn:hover {
  text-decoration: underline;
}

.create-header {
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.create-header h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 0;
}

.create-form {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.form-control {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  background-color: #f5f8ff;
}

.form-control:focus {
  border-color: #3e8ef7;
  outline: none;
  box-shadow: 0 0 0 2px rgba(62, 142, 247, 0.2);
}

textarea.form-control {
  resize: vertical;
  min-height: 200px;
}

.error-message {
  color: #f44336;
  font-size: 14px;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.btn {
  padding: 12px 24px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  border: none;
  transition: background-color 0.3s;
}

.btn-save {
  background-color: #4CAF50;
  color: white;
}

.btn-save:hover {
  background-color: #43A047;
}

.btn-cancel {
  background-color: #f44336;
  color: white;
}

.btn-cancel:hover {
  background-color: #e53935;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn:disabled:hover {
  background-color: inherit;
}

@media (max-width: 768px) {
  .container {
    padding: 15px;
  }
  
  .create-header h1 {
    font-size: 20px;
  }
  
  .form-group label {
    font-size: 14px;
  }
  
  .form-control {
    font-size: 14px;
    padding: 10px;
  }
  
  .btn {
    font-size: 14px;
    padding: 10px 20px;
  }
}
</style> 